import pygame
from pygame.locals import *
from mastergoal.common.piece import *
from mastergoal.rules.ruleengine import RuleEngine
from util.vector import *
import os

class UIEvent:
    
    """ Handle all game events """
    
    def __init__(self, game):
        self.game = game
        self.piece_entity = None
    
    def __square_clicked(self,pos):
        """ Checks if square is selected """
        grid_coords = self.game.grid.get_position(pos)
        if grid_coords:
            key = str(grid_coords[0]) + '_' + str(grid_coords[1])
            self.sqr_selected = self.game.grid.board[key]
            return grid_coords
        
        return None
    
    
    def __piece_clicked(self,pos):
        """ Checks if a piece is selected """
        for obj in self.game.pieces_gui:
            if obj.position.collidepoint(pos):
                self.piece_entity = obj
                return obj
        
        return None  
    
    
    def handle(self,event):
        """ Handle UI Events """
      
        # Save mouse coordinates
        coords = pygame.mouse.get_pos()
            
        # Piece clicked
        if self.__piece_clicked(coords):
                
        # Check if a piece can be selected according to game state
                     
                
            print self.piece_entity.piece
            
            
        # Square clicked    
        elif self.__square_clicked(coords):
                # 
            if self.piece_entity:
                    
                # Check rules before moving
                origin = (self.piece_entity.piece.square.row, self.piece_entity.piece.square.col)
                destination = (self.game.grid.get_position(self.sqr_selected))
                
                ball_move = player_move = (False,None)
                    
                # What type of piece are we moving?
                try:
                    self.piece_entity.piece.id
                except AttributeError:
                    # Moving ball
                    ball_move = RuleEngine.valid_ball_movement(self.piece_entity.piece, destination, self.game.state)
                else:
                    # Moving piece
                    player_move = RuleEngine.valid_player_movement(self.piece_entity.piece, destination, self.game.state)
 
                print player_move
                # Apply moves
                # Check ball move 
                if ball_move[0]:
                     self.game.state.do_move_ball(ball_move[1])
                # Check player response
                elif player_move[0]:
                     self.game.state.do_move_player(player_move[1])
                        
                    
                    
                #destination = Vector(*coords) - Vector(*self.piece_entity.image.get_size())/2.
                #self.piece_entity.initial_pos = Vector(self.piece_entity.position.left, self.piece_entity.position.top)
                #self.piece_entity.destination = coords
                    
                piece_row, piece_col = self.game.grid.get_position(coords)
                key = str(piece_row) + '_' +str(piece_col)
                dest = self.game.grid.board[key]
                self.piece_entity.destination = (dest.left, dest.top)
                #print self.piece_entity.destination

                    
                #piece_square = self.piece_entity.piece.square
                #key = str(piece_square.row) + '_' +str(piece_square.col)
                #origin = self.game.grid.board[key]
                #piece_coords = (origin.left, origin.top)
                piece_coords = self.piece_entity.get_coords()
                    
                self.piece_entity.move_delta = [ abs(piece_coords[i]-self.piece_entity.destination[i]) for i in range(2)]
                print self.piece_entity.move_delta
                #exit()
                self.piece_entity.move_current = [0,0]
                    
                self.piece_entity.heading = Vector.from_points(piece_coords, self.piece_entity.destination)
                self.piece_entity.heading.normalise() * self.game.speed

                #print self.piece_entity.heading
                self.piece_entity.heading *= self.game.speed
                    
                self.piece_entity.moving = True
                #self.piece_entity.square = self.sqr_selected

                #print self.game.grid.get_position((self.sqr_selected.left, self.sqr_selected.top))
